import Vue from "vue";
import { BootstrapVue, BootstrapVueIcons } from "bootstrap-vue";
import PortalVue from 'portal-vue'
import "bootstrap/dist/css/bootstrap.css"
import 'bootstrap-vue/dist/bootstrap-vue.css'
import "../css/index.scss";
import IEcharts from "vue-echarts-v3/src/full";

Vue.use(BootstrapVue);
Vue.use(BootstrapVueIcons)
Vue.use(PortalVue);

let conn;
let colors = ['#fac858', '#ee6666' ,'#5470c6', '#9a60b4', '#91cc75', '#73c0de', '#3ba272', '#fc8452', '#ea7ccc'];
let app = new Vue({
    components:{
        IEcharts
    },
    el:"#app",
    data:function () {
        let data = {
            tableConfig: {
                fields: [
                    {key: "item_type", label: "类型", class: 'text-center'},
                    {key: "rank_type", label: "星级", class: 'text-center'},
                    {key: "name", label: "名称", class: 'text-center'},
                    {key: "time", label: "祈愿时间", class: 'text-center'}
                ],
                fields2: [
                    {key: "gacha_type", label: "池子", class: 'text-center'},
                    {key: "item_type", label: "类型", class: 'text-center'},
                    {key: "rank_type", label: "星级", class: 'text-center'},
                    {key: "name", label: "名称", class: 'text-center'},
                    {key: "time", label: "祈愿时间", class: 'text-center'}
                ],
            },
            gachaType: {
                301: "角色池",
                400: "角色池2"
            },
            exporting:false,
            showBottom:false,
            logs:[],
            connected:false,
            gachaData:{},
            original:{},
            config:{
                saveGacha:false
            },
            colors:colors
        };
        try {
            let l = localStorage["config"];
            let d = JSON.parse(l);
            data.config.saveGacha = d.saveGacha;
        }catch (e) {

        }
        return data;
    },
    computed: {
        downloadJSONUrl(){
            let blob = new Blob([JSON.stringify(this.original)],{type:"application/json"});
            let url = URL.createObjectURL(blob);
            return url;
        },
        hasData(){
            let has = false;
            for (let i=0,keys=Object.keys(this.gachaData),size=keys.length;i<size;i++){
                if (this.gachaData[keys[i]] && Array.isArray(this.gachaData[keys[i]]) && this.gachaData[keys[i]].length>0){
                    has = true;
                    break;
                }
            }
            return has;
        },
        saveGacha:{
            get(){
                return this.config.saveGacha;
            },
            set(val){
                this.config.saveGacha = val;
                localStorage["config"] = JSON.stringify(this.config);
            }
        }
    },
    methods:{
        downloadExcel(){
            conn.send(JSON.stringify({code:2}));
        },
        loadData(){
            if (this.connected){
                conn.send(JSON.stringify({code:0}));
            }else {
                this.$bvToast.toast('ws连接已断开，请刷新浏览器后再试！', {
                    title: '错误',
                    variant: 'danger',//danger,warning,info,primary,secondary,default
                    solid: true,
                    toaster:"b-toaster-top-center"
                });
            }
        },
        setConnected(isConnected){
            this.connected = isConnected;
            if (isConnected){
                this.$bvToast.toast('ws连接成功', {
                    title: '提示',
                    variant: 'success',//danger,warning,info,primary,secondary,default
                    solid: true,
                    toaster:"b-toaster-top-center"
                });
            }else {
                this.$bvToast.toast('ws连接断开，请尝试刷新浏览器', {
                    title: '错误',
                    variant: 'danger',//danger,warning,info,primary,secondary,default
                    solid: true,
                    toaster:"b-toaster-top-center"
                });
            }
        },
        selectFile(e){
            let file = e.target.files[0];
            if (!file) {
                this.$bvToast.toast('文件无效', {
                    title: '错误',
                    variant: 'danger',//danger,warning,info,primary,secondary,default
                    solid: true,
                    toaster:"b-toaster-top-center"
                });
                return;
            }
            let reader = new FileReader();
            reader.onload = ()=>{
                if (reader.result && typeof reader.result==="string"){
                    let regexp = /(https.+?game_biz=hk4e.+?)\x00/ig;
                    let match = reader.result.matchAll(regexp);

                    let param={};
                    for (let item of match){
                        if (Array.isArray(item) && item.length>=2){
                            try {
                                let u = new URL(item[1]);
                                let authKeyVer = u.searchParams.get("authkey_ver"),lang=u.searchParams.get("lang"),authKey=u.searchParams.get("authkey");
                                if (authKeyVer && lang && authKey){
                                    if (u.host.includes("webstatic-sea") || u.host.includes("hk4e-api-os")){
                                        param.url = "https://hk4e-api-os.mihoyo.com";
                                    }else {
                                        param.url = "https://hk4e-api.mihoyo.com";
                                    }
                                    param["auth_key_ver"] = authKeyVer;
                                    param["lang"] = lang;
                                    param["auth_key"] = authKey;
                                }
                            }catch (e) {

                            }
                        }
                    }
                    if (!param.hasOwnProperty("url") || param.url==="" || !param.hasOwnProperty("auth_key") || !param.auth_key){
                        this.$bvToast.toast('分析祈愿历史记录网址失败，请重新在游戏中打开祈愿界面的详情或者历史记录后再试！', {
                            title: '错误',
                            variant: 'danger',//danger,warning,info,primary,secondary,default
                            solid: true,
                            toaster:"b-toaster-top-center"
                        });
                        return
                    }
                    if (this.connected){
                        conn.send(JSON.stringify({code:1,param:param,save_data:this.saveGacha}));
                    }else {
                        this.$bvToast.toast('ws连接已断开，请刷新浏览器后再试！', {
                            title: '错误',
                            variant: 'danger',//danger,warning,info,primary,secondary,default
                            solid: true,
                            toaster:"b-toaster-top-center"
                        });
                    }
                }else {
                    this.$bvToast.toast('文件无效', {
                        title: '错误',
                        variant: 'danger',//danger,warning,info,primary,secondary,default
                        solid: true,
                        toaster:"b-toaster-top-center"
                    });
                }
            };
            reader.readAsText(file);
            e.target.value = null;
        },
        addLog(log){
            this.showBottom = true;
            this.logs.push(log);
        }
    },
    mounted() {
        if (window.hasOwnProperty("WebSocket") && window.WebSocket){
            conn = new WebSocket(location.href.replace("http","ws"));
            conn.onclose = ev => {
                // console.log(ev)
                this.setConnected(false);
                this.addLog(`ws连接已关闭(${ev.code})，无法加载数据`)
                console.log(ev)
            }
            conn.onerror = ev => {
                // console.log("error",ev)
                // this.setConnected(false);
                // this.addLog(`连接已关闭，无法加载数据`)
            }
            conn.onopen = ev => {
                this.setConnected(true);
                this.addLog(`ws连接已打开，可以加载数据了`)
            }
            conn.onmessage = ev => {
                if (typeof ev.data==="string"){
                    try {
                        let message = JSON.parse(ev.data);
                        if (message.code===1){
                            this.addLog(message.message);
                        }else if (message.code===-1){
                            this.addLog(message.message);
                            this.$bvToast.toast(message.message, {
                                title: '错误',
                                variant: 'danger',//danger,warning,info,primary,secondary,default
                                solid: true,
                                toaster:"b-toaster-top-center"
                            });
                        }else if (message.code===0){
                            this.original = message.data;
                            this.gachaData = formatGacha(message.data);
                        }
                    }catch (e){}
                }else if (ev.data instanceof Blob){
                    let url = URL.createObjectURL(ev.data);
                    let aLink = document.createElement('a');
                    aLink.href = url;
                    aLink.download = '祈愿记录-'+formatTime(new Date(),"yyyyMMdd-hhmmss")+'.xlsx'; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
                    let event;
                    if(window.MouseEvent) {
                        event = new MouseEvent('click');
                    } else {
                        event = document.createEvent('MouseEvents');
                        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    }
                    aLink.dispatchEvent(event);
                }
            }
        }
    }
});

function formatGacha(data){
    let list = JSON.parse(JSON.stringify(data));
    let result = {
        list:{},
        chart:[]
    };
    let totalStatisticsData = newStatisticsData("总体");
    let keys = Object.keys(list).sort((a,b)=>a.localeCompare(b));
    for (let i=0,size=keys.length;i<size;i++){
        let key = keys[i];
        let g = list[key];
        if (g.length<=0) continue;
        let statisticsData = newStatisticsData(key);
        let count = g.length;
        statisticsData.allCount = count;    //总抽数
        totalStatisticsData.allCount += count;  //总抽数
        for (let index=count-1;index>=0;index--){
            let d = g[index];
            if (d.rank_type==="5"){ //是5星
                d._rowVariant = "warning";
                statisticsData.fiveHistory.push(d.name+"["+(statisticsData.missFiveCount+1)+"]");   //记录5星和第多少抽
                totalStatisticsData.fiveHistory.push(d.name+"["+(statisticsData.missFiveCount+1)+"]");   //记录5星和第多少抽
                statisticsData.missFiveCount = 0;   //重置多少抽未出5星数据
                if (d.item_type==="武器"){
                    statisticsData.fiveArmsCount++;
                    totalStatisticsData.fiveArmsCount++;
                }else {
                    statisticsData.fiveCharacterCount++;
                    totalStatisticsData.fiveCharacterCount++;
                }
            }else {
                statisticsData.missFiveCount++;
            }
            if (d.rank_type==="4"){
                d._rowVariant = "info";
                statisticsData.missFourCount = 0;
                if (d.item_type==="武器"){
                    statisticsData.fourArmsCount++;
                    totalStatisticsData.fourArmsCount++;
                }else {
                    statisticsData.fourCharacterCount++;
                    totalStatisticsData.fourCharacterCount++;
                }
            }else {
                statisticsData.missFourCount++;
            }
            if (d.rank_type==="3" && d.item_type==="武器"){
                statisticsData.threeArmsCount++;
                totalStatisticsData.threeArmsCount++;
            }
            //记录最早一抽和最晚一抽的时间
            let t = new Date(Date.parse(d.time));
            if (statisticsData.earliestTime==="" || t < statisticsData.earliestTimeDate){
                statisticsData.earliestTime = formatTime(t,"yyyy-MM-dd");
                statisticsData.earliestTimeDate = t;
            }
            if (statisticsData.latestTime==="" || t > statisticsData.latestTimeDate){
                statisticsData.latestTime = formatTime(t,"yyyy-MM-dd");
                statisticsData.latestTimeDate = t;
            }
            if (totalStatisticsData.earliestTime==="" || t < totalStatisticsData.earliestTimeDate){
                totalStatisticsData.earliestTime = formatTime(t,"yyyy-MM-dd");
                totalStatisticsData.earliestTimeDate = t;
            }
            if (totalStatisticsData.latestTime==="" || t > totalStatisticsData.latestTimeDate){
                totalStatisticsData.latestTime = formatTime(t,"yyyy-MM-dd");
                totalStatisticsData.latestTimeDate = t;
            }
        }
        result.chart.push({
            statistics:statisticsData,
            chart:newPieData(statisticsData)
        });
        totalStatisticsData.missFiveCount += statisticsData.missFiveCount;
        if (statisticsData.fiveHistory.length>0){
            statisticsData.averageFiveCount = ((count-statisticsData.missFiveCount) / statisticsData.fiveHistory.length).toFixed(2);
        }else {
            statisticsData.averageFiveCount = 0;
        }
        if (statisticsData.fourArmsCount + statisticsData.fourCharacterCount > 0){
            statisticsData.averageFourCount = ((count-statisticsData.missFourCount) / (statisticsData.fourArmsCount+statisticsData.fourCharacterCount)).toFixed(2);
        }
        result.list[key] = {
            page:1,
            data:g
        };
    }
    if (totalStatisticsData.fiveHistory.length>0){
        totalStatisticsData.averageFiveCount = ((totalStatisticsData.allCount-totalStatisticsData.missFiveCount) / totalStatisticsData.fiveHistory.length).toFixed(2);
    }else {
        totalStatisticsData.averageFiveCount = 0;
    }
    if (totalStatisticsData.fourArmsCount + totalStatisticsData.fourCharacterCount > 0){
        totalStatisticsData.averageFourCount = ((totalStatisticsData.allCount-totalStatisticsData.missFourCount) / (totalStatisticsData.fourArmsCount+totalStatisticsData.fourCharacterCount)).toFixed(2);
    }
    result.chart.unshift({
        statistics:totalStatisticsData,
        chart:newPieData(totalStatisticsData)
    });
    return result;
}

function newPieData(data){
    let result = {
        title: [{
            text: data.name,
            left: "center",
            subtext: data.earliestTime + " - " + data.latestTime
        }],
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b} : {c} ({d}%)"//a:series.name,b:series.data.name,c:series.data.value,d:百分比
        },
        legend: {
            orient: "horizontal",
            left: "center",
            data: [],
            selected: {},
            top: "50px"
        },
        series: [
            {
                name: data.name,
                type: "pie",
                radius: "55%",
                center: ["50%", "63%"],
                data: [],
                labelLine: {
                    length: 10,
                    length2: 10
                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: "rgba(0, 0, 0, 0.5)"
                    }
                }
            }
        ],
        color:colors
    }
    if (data.fiveArmsCount>0){
        let name = "5星武器";
        result.legend.data.push(name);
        result.legend.selected[name] = true;
        result.series[0].data.push({ value: data.fiveArmsCount, name: name });
    }
    if (data.fiveCharacterCount>0){
        let name = "5星角色";
        result.legend.data.push(name);
        result.legend.selected[name] = true;
        result.series[0].data.push({ value: data.fiveCharacterCount, name: name });
    }
    if (data.fourArmsCount>0){
        let name = "4星武器";
        result.legend.data.push(name);
        result.legend.selected[name] = true;
        result.series[0].data.push({ value: data.fourArmsCount, name: name });
    }
    if (data.fourCharacterCount>0){
        let name = "4星角色";
        result.legend.data.push(name);
        result.legend.selected[name] = true;
        result.series[0].data.push({ value: data.fourCharacterCount, name: name });
    }
    if (data.threeArmsCount>0){
        let name = "3星武器";
        result.legend.data.push(name);
        result.legend.selected[name] = false;
        result.series[0].data.push({ value: data.threeArmsCount, name: name });
    }
    return result;
}

function newStatisticsData(name){
    return {
        name:name,//名称
        allCount:0, //总共多少抽
        missFiveCount:0,//已多少抽未出5星
        missFourCount:0,//已多少抽未出4星
        earliestTime:"",//最早一抽的时间
        earliestTimeDate:0,
        latestTime:"",//最晚一抽的时间
        latestTimeDate:0,
        fiveArmsCount:0,//5星武器个数
        fiveCharacterCount:0,//5星角色个数
        fourArmsCount:0,//4星武器个数
        fourCharacterCount:0,//4星角色个数
        threeArmsCount:0,//3星武器个数
        fiveHistory:[],//5星历史记录（x[y],括号内为第多少抽）
        averageFiveCount:0,//5星平均出货（所有5星第多少抽相加除以5星个数，或总抽数减去最后未出5星数，再除以5星个数）
        averageFourCount:0,//4星平均出货(总抽数减去最后未出4星数减去5星数，再除以4星个数)
    }
}

function formatTime(time,fmt) {
    var o = {
        "M+" : time.getMonth()+1,                 //月份
        "d+" : time.getDate(),                    //日
        "h+" : time.getHours(),                   //小时
        "m+" : time.getMinutes(),                 //分
        "s+" : time.getSeconds(),                 //秒
        "q+" : Math.floor((time.getMonth()+3)/3), //季度
        "S"  : time.getMilliseconds()             //毫秒
    };
    if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (time.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(let k in o) {
        if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length===1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
    return fmt;
}